/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkRtsp/MkRtspPublisher.h"
#include <MkUtil/MkLog.h>
#include "MkEvent/MkEvent.h"
#include "MkUtil/MkThread.h"
#include "MkRtsp/MkRtspSubSession.h"
#include "MkEvent/MkTimer.h"
#include "MkEvent/MkEventPool.h"
#include "MkRtp/MkRtpServerPool.h"
#include "MkMedia/MkFileSource.h"
#include <signal.h>

CMkRtspPublisher *g_pPublisher = nullptr;

void SamplePublishTcp264()
{
#ifdef _WIN32
    MkString RtspUrl = "rtsp://192.168.0.24/live/test";
    MkString FileName = "C:/Workspace/media/aa.264";
#else
    MkString RtspUrl = "rtsp://192.168.0.24/live/test";
    MkString FileName = "/root/wzg/mksource/bin/media/aa.264";
#endif
    MkLogInitLevel("TestTcpServer", TO_SCREEN);
    MkLogChangeLevel(LOG_DEBUG);
    CMkEventPool Pool;
    CMkTimer  Timer;
    CMkTimer* pTimer = &Timer;
    Pool.Start(1);
    CMkRtpServerPool *pRtpPool = new CMkRtpServerPool(&Pool, &Timer);
    pRtpPool->SetBeginPort(40000);
    pRtpPool->Start();
    FILE *fp = fopen(FileName.c_str(), "rb");
    CMkH264FileSource *pFileSource = new CMkH264FileSource(fp, pTimer);
    g_pPublisher = new CMkRtspPublisher(Pool.GetFreeEvent(), pTimer, pRtpPool->GetVecRtpUdpServer(), [pTimer](CMkTcpClient *pClient)
    {
        MkDebugLog("player removed\n");
        pTimer->LoopBreak();
        pClient->DeleteLater();
    });

    g_pPublisher->Start(RtspUrl, TRUE, pFileSource->GetVideoParam(), pFileSource->GetAudioParam(), [pFileSource](Uint32 ErrorCode) {
        pFileSource->StartMediaSource([](CMkMediaSource* pMediaSource, Uint32 ErrorCode) {
            return NoneError;
        }, [pFileSource](const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam) {
            if (g_pPublisher) {
                g_pPublisher->SendEsPacket(pFileSource, EsPacket);
            }
            return NoneError;
        });
    });
    pTimer->Dispatch();
    pRtpPool->Stop();
    Pool.Stop();
}

void SamplePublishUdp264()
{

}

int main(int argc, char** argv)
{
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
#endif
    SamplePublishTcp264();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}




